import { useRef } from 'react';
import { KeyOutlined, LeftOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin } from 'antd';
import { useModel } from 'umi';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import type { MenuInfo } from 'rc-menu/lib/interface';
import avatarUrl from './avatar.png';
import { useKeycloak } from '@react-keycloak/web';
import { CURRENT_GROUP_KEY } from '@/constants';
import type { BasicModalFormRef } from '../BasicModalForm';
import BasicModalForm from '../BasicModalForm';
import { updatePassword, crud } from '@/pages/User/api';
import { handleUpdate } from '@/utils/handler';
import UserInfoForm from '../UserForm/UserInfoForm';
import PasswordForm from '../UserForm/PasswordForm';

export default () => {
  const { initialState, setInitialState, refresh } = useModel('@@initialState');

  const { keycloak } = useKeycloak();

  const settingRef = useRef<BasicModalFormRef>(null);
  const passwordRef = useRef<BasicModalFormRef>(null);

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.id || !currentUser.currentGroup) {
    return loading;
  }

  const {
    id,
    name,
    firstName,
    lastName,
    email,
    groups = [],
    currentGroup = '',
    currentGroupName = '',
  } = currentUser;

  const onGroupChange = (newGroupId: string) => {
    if (newGroupId === currentGroup) {
      return;
    }
    const newGroup = groups.find((item) => item.tenant_id === newGroupId);
    if (newGroup) {
      localStorage.setItem(CURRENT_GROUP_KEY, newGroup.tenant_id);
      setInitialState({
        ...initialState,
        currentUser: {
          ...currentUser,
          currentGroup: newGroup.tenant_id,
          currentGroupName: newGroup.tenant_name,
        },
      });
      refresh();
    }
  };

  const onMenuClick = (event: MenuInfo) => {
    const { key } = event;
    if (key === 'info') {
      settingRef.current?.open();
      return;
    }
    if (key === 'password') {
      passwordRef.current?.open();
      return;
    }
    if (key === 'logout') {
      keycloak.logout();
      return;
    }
    onGroupChange(key);
    return;
  };

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[currentGroup]} onClick={onMenuClick}>
      <Menu.SubMenu key="groups" icon={<LeftOutlined />} title={currentGroupName}>
        {groups.map((group) => (
          <Menu.Item key={group.tenant_id}>{group.tenant_name}</Menu.Item>
        ))}
      </Menu.SubMenu>
      <Menu.Divider />
      <Menu.Item key="info">
        <SettingOutlined />
        个人信息
      </Menu.Item>
      <Menu.Item key="password">
        <KeyOutlined />
        修改密码
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );

  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={avatarUrl} alt="avatar" />
          <span className={`${styles.name} anticon`}>{name}</span>
        </span>
      </HeaderDropdown>
      <BasicModalForm
        ref={settingRef}
        title={'个人设置'}
        onSubmit={(data) => handleUpdate({ ...data, id }, crud.update)}
        onReload={() => refresh()}
        values={{ first_name: firstName, last_name: lastName, email }}
      >
        <UserInfoForm isPersonal={true} isAdd={false} />
      </BasicModalForm>
      <BasicModalForm
        ref={passwordRef}
        title={'修改密码'}
        onSubmit={(data) => handleUpdate({ ...data, id, need_renew: false }, updatePassword)}
        onReload={() => keycloak.logout()}
        values={currentUser}
      >
        <PasswordForm isPersonal={true} />
      </BasicModalForm>
    </>
  );
};
